package com.thirdsdk.baidu;

import android.content.Context;
import android.content.Intent;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

/**
 * 地图位置监听类
 * 
 * @author Administrator
 * 
 */
public class MyLocationListener implements BDLocationListener {
	private boolean isFirstLoc = true;
	private MapView mMapView;
	private BaiduMap mBaiduMap;
	private Context context;

	public MyLocationListener(Context context, MapView mMapView,
			BaiduMap mBaiduMap) {
		this.context = context;
		this.mMapView = mMapView;
		this.mBaiduMap = mBaiduMap;
	}

	public MyLocationListener(Context context){
		this.context = context;
	}
	@Override
	public void onReceiveLocation(BDLocation location) {
		/*mapView销毁后不再处理新接收的位置*/
		if (location == null)
			return;
		/*发送广播*/
		sendMapBroadcast(location);
		/*构造定位数据*/
		MyLocationData locData = new MyLocationData.Builder()
				.accuracy(location.getRadius())
				/*此处设置开发者获取到的方向信息，顺时针0-360*/
				.direction(100).latitude(location.getLatitude())
				.longitude(location.getLongitude()).build();
		if (mBaiduMap != null) {
			mBaiduMap.setMyLocationData(locData);
			/*第一位定位时，将地图位置移动到当前位置*/
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);
			}
		}
	}
	

	/**
	 * 发送广播
	 * 
	 * @param location
	 */
	private void sendMapBroadcast(BDLocation location) {
		Intent mIntent = new Intent("MapService");
		mIntent.putExtra("lon", location.getLongitude());
		mIntent.putExtra("lat", location.getLatitude());
		mIntent.putExtra("address", location.getAddrStr());
		mIntent.putExtra("city", location.getCity());
		/*发送广播*/
		context.sendBroadcast(mIntent);
	}
}
